package application;

import java.io.IOException;
import java.io.Serializable;
import java.net.Socket;
import java.net.UnknownHostException;

import net.jxta.peergroup.PeerGroup;
import net.jxta.protocol.PipeAdvertisement;
import net.jxta.socket.JxtaSocket;

public class MachineID implements Serializable{

	private static final long serialVersionUID = 415915641695150066L;
	private PeerGroup pGroup = null;
	private PipeAdvertisement pAdv = null;
	private String serverName = null;
	private int serverPort = 0;
	
	public MachineID( String serverName, int serverPort ){
		this.serverName = serverName;
		this.serverPort = serverPort;
	}
	
	public MachineID( PeerGroup peerGroup, PipeAdvertisement pipeAdv ){
		pGroup = peerGroup;
		pAdv = pipeAdv;
	}
	
	boolean isServent(){
		return serverName == null;
	}
	
	boolean isServer(){
		return !isServent();
	}

	public PeerGroup getpGroup() {
		return pGroup;
	}

	public void setpGroup(PeerGroup pGroup) {
		this.pGroup = pGroup;
	}

	public PipeAdvertisement getpAdv() {
		return pAdv;
	}

	public void setpAdv(PipeAdvertisement pAdv) {
		this.pAdv = pAdv;
	}

	public String getServerName() {
		return serverName;
	}

	public void setServerName(String serverName) {
		this.serverName = serverName;
	}

	public int getServerPort() {
		return serverPort;
	}

	public void setServerPort(int serverPort) {
		this.serverPort = serverPort;
	}
	
	public String toString(){
		if( isServent() ){
			return getPeerName();// " servent en peer group " + pGroup.getPeerGroupName() + " with pipe adv " + pAdv.getName();
		}
		else{
			return " server " + serverName + " con puerto " + serverPort;
		}
	}

	public Socket createSocket() throws UnknownHostException, IOException {
		
		if( serverName != null ){
			return new Socket( serverName, serverPort );
		}
		else{
			return new JxtaSocket(pGroup,
                    // no specific peerid
                    null,
                    pAdv,
                    //timeout after a minute
                    60000,
                    // reliable connection
                    true);
		}
	}

	public String getPeerName() {
		return pAdv.getDescription();
	}
}
